
from whiff.middleware import misc
from whiff.middleware import setInnerHtml
from whiff.middleware import whiffColorize
from whiff.middleware import pygmentsColorize
from whiff import resolver

class embed(misc.javaScriptGenerator):
    def __init__(self,
                 targetName,
                 page
                 ):
        self.targetName = targetName
        self.page = page
    def __call__(self, env, start_response):
        targetName = self.param_value(self.targetName, env)
        try:
            # do not try this at home (it's a hack)
            ##pr "page is", self.page
            #pr "args are", self.page.arguments.keys()
            pageArg = self.page.arguments["page"]
            #pr "pageArg dir", dir(pageArg)
            pageSrc = pageArg.text
        except:
            pageSrc = self.param_text(self.page)
        pageHtml = self.param_value(self.page,env)
        #pageQuoted = resolver.quote(pageHtml)
        srcName = targetName+"_source"
        htmlName = targetName+"_html"
        quoteName = targetName+"_quote"
        srcApp = whiffColorize.whiffColorize(page=pageSrc, lexer="html")
        srcApp = setInnerHtml.setInnerHtml(elementName=targetName, page=srcApp)
        srcApp = self.param_value(srcApp, env)
        htmlApp = self.param_value(setInnerHtml.setInnerHtml(elementName=targetName, page=pageHtml), env)
        quoteApp = pygmentsColorize.pygmentsColorize(page=pageHtml, lexer="html")
        quoteApp = self.param_value(setInnerHtml.setInnerHtml(elementName=targetName, page=quoteApp), env)
        start_response("200 OK", [('Content-Type', 'application/javascript')])
        yield srcName
        yield " = function() {"
        yield srcApp
        yield "};\n"
        yield htmlName
        yield " = function() { "
        yield htmlApp
        yield "};\n"
        yield quoteName
        yield " = function() {"
        yield quoteApp
        yield "};\n"

__middleware__ = embed

testPage = """
        An <em>html</em> page with the header_trailer filter disabled
"""

def test():
    e = embed("TARGET", testPage)
    result = e({}, misc.ignore)
    sresult = "".join(list(result))
    print "test result"
    print sresult

if __name__=="__main__":
    test()
